package tq.com.tqstudent;

import android.app.Application;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.multidex.MultiDex;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.lib.common.utils.AppUtil;
import com.lib.common.utils.LogUtil;
import com.lib.common.utils.SCDatabase;
import com.lib.common.utils.SPUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.HttpParams;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;
import tq.com.tqandroidim.TQIM;
import tq.com.tqstudent.bean.UserInfo;
import tq.com.tqstudent.utils.CrashHandler;

/**
 * Created by yangju on 2018/11/17.
 */

public class App extends Application {
    private static App app;
    private static IWXAPI mWxApi;

    public final static App getApp(){
        return app;
    }

    public static IWXAPI getWxApi(){
        return mWxApi;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        SCDatabase.shareObject().init(this);
        CrashHandler.getInstance().init(getApplicationContext());

        registerToWX();

        initPushService(this);
//        SCLogin.shareInstance().init();

//        SCUMengHelper.initPush(this);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);

        OkGo.getInstance().init(this)
                .setOkHttpClient(initOkGoBuilder())             //建议设置OkHttpClient，不设置将使用默认的
                .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间，默认永不过期，可以不传
                .setRetryCount(0);                               //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
//                .addCommonHeaders(headers)                      //全局公共头
//                .addCommonParams(initOkGoParams());             //全局公共参数
    }

    private OkHttpClient initOkGoBuilder(){
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //全局的读取超时时间
        builder.readTimeout(Constants.OKGO_READ_TIME_OUT, TimeUnit.SECONDS);
        //全局的写入超时时间
        builder.writeTimeout(Constants.OKGO_WRITE_TIME_OUT, TimeUnit.SECONDS);
        //全局的连接超时时间
        builder.connectTimeout(Constants.OKGO_CONNECT_TIME_OUT, TimeUnit.SECONDS);

        logBuilder(builder);
        return builder.build();
    }

    private HttpParams initOkGoParams(){
        HttpParams params = new HttpParams();
        params.put("platform", "android");     //param支持中文,直接传,不要自己编码
        params.put("versionCode", AppUtil.getVersionCode(this));

        return params;
    }

    private void logBuilder(OkHttpClient.Builder builder){
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        //log打印级别，决定了log显示的详细程度
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        //log颜色级别，决定了log在控制台显示的颜色
        loggingInterceptor.setColorLevel(Level.OFF);
        builder.addInterceptor(loggingInterceptor);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }

    static {
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsHeader(context);
            }
        });

        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsFooter(context);
            }
        });
    }

    private void registerToWX() {
        //第二个参数是指你应用在微信开放平台上的AppID
        mWxApi = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID, false);
        // 将该app注册到微信
        mWxApi.registerApp(Constants.WX_APP_ID);
    }

    /** 网络请求地址 */
    public static String getHttpUrl(String url){
        return UserInfo.getHttpUrl() + "/" + url;
    }

    /** 文件地址 */
    public static String getFileUrl(String id){
        return UserInfo.getFileHttpUrl() + Constants.FILE_URL + id;
    }

    /** 上传文件的路径 */
    public static String getUploadUrl(){
        return UserInfo.getFileHttpUrl() + Constants.UPLOAD_URL;
    }

    /** 开始im链接 */
    public static void startImWhenLogin(){
        String imURL = "";
        String ip = "";
        int port = 5300;

        try{
            imURL = UserInfo.getIMHttpUrl();
            ip = imURL.split(":")[0];
            port = Integer.parseInt(imURL.split(":")[1]);
        } catch (Exception e){
            e.printStackTrace();
            ip = Constants.HTTP_IM_IP_URL;
            port = Constants.HTTP_IM_PORT_URL;
        }

        TQIM.getShareIm().getConfigure().setIp(ip);
        TQIM.getShareIm().getConfigure().setPort(port);
        TQIM.getShareIm().getConfigure().setToken(UserInfo.getToken());
        TQIM.getShareIm().start();
    }

    /** 停止im链接 */
    public static void stopImWhenLogout(){
        TQIM.getShareIm().stop();
    }

    private void initPushService(final Context applicationContext) {
        PushServiceFactory.init(applicationContext);
        final CloudPushService pushService = PushServiceFactory.getCloudPushService();
        pushService.register(applicationContext, new CommonCallback() {
            @Override
            public void onSuccess(String response) {
                SPUtils.getInstance(getApp()).putString(Constants.ALI_PUSH_DEVICE_ID, pushService.getDeviceId());
                LogUtil.e("init cloudchannel success, response: "+response+" | deviceID:"+pushService.getDeviceId());
                //setConsoleText("init cloudchannel success");
            }
            @Override
            public void onFailed(String errorCode, String errorMessage) {
                LogUtil.e("init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
                //setConsoleText("init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
            }
        });
    }
}
